/**
 *
 */
package org.jim.server.command.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.jim.common.*;
import org.jim.common.cache.redis.JedisTemplate;
import org.jim.common.cache.redis.RedisCache;
import org.jim.common.cache.redis.RedisCacheManager;
import org.jim.common.message.MessageHelper;
import org.jim.common.packets.Command;
import org.jim.common.packets.Group;
import org.jim.common.packets.RespBody;
import org.jim.common.packets.User;
import org.jim.common.packets.UserReqBody;
import org.jim.common.utils.ImKit;
import org.jim.common.utils.JsonKit;
import org.jim.server.command.AbstractCmdHandler;
import org.tio.core.ChannelContext;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 版本: [1.0]
 * 功能说明: 获取用户信息消息命令
 * @author : WChao 创建时间: 2017年9月18日 下午4:08:47
 */
public class UserReqHandler extends AbstractCmdHandler implements ImConst {

    RedisCache groupCache = RedisCacheManager.register(ImConst.GROUP, Integer.MAX_VALUE, Integer.MAX_VALUE);

    private final String SUBFIX = ":";

    @Override
    public ImPacket handler(ImPacket packet, ChannelContext channelContext) throws Exception {
        return doTemp(packet, channelContext);
    }

    // Alex20191110：简化获取在线用户列表的业务实现最大限度提高性能。
    // (现聊天室只有一个默认群组groupid:1、前端页面除了请求“群组在线用户列表”暂无其他类型用户列表的请求)
    private ImPacket doTemp(ImPacket packet, ChannelContext channelContext) throws Exception {
//        long start, end;
//        start = System.currentTimeMillis();

        UserReqBody userReqBody = JsonKit.toBean(packet.getBody(), UserReqBody.class);
//        //(0:所有在线用户,1:所有离线用户,2:所有用户[在线+离线]);
        ImSessionContext imSessionContext = (ImSessionContext) channelContext.getAttribute();
        //消息持久化助手;
//        MessageHelper messageHelper = imConfig.getMessageHelper();
        User user = imSessionContext.getClient().getUser();
        String userId = user.getId();
        String groupid = user.getGroupId();
        Group group = groupCache.get(groupid + SUBFIX + INFO, Group.class);
        if (group != null) {
            List<User> allUsers = ImAio.getAllOnlineUser();
            List<String> userIds = new ArrayList<>(allUsers.size());
            for (User u : allUsers) {
                userIds.add(u.getId());
            }
            List<User> users = new ArrayList<User>();

            Map<String, String> userInfo = new HashMap<>();
            Map<String, String> userInfoKeys = new HashMap<>();
            for (String userid : userIds) {
                userInfoKeys.put(userid, USER + SUBFIX + userid + SUBFIX + INFO);
            }
            try {
                userInfo = JedisTemplate.me().batchGetKeysToKeyMap(userInfoKeys);
                for (Map.Entry<String, String> entry : userInfo.entrySet()) {
                    User u = JSON.parseObject(entry.getValue(), User.class);
                    users.add(u);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            group.setUsers(users);
        }
        user = new User();
        user.setId(userId);
        user.setGroupId(groupid);
//        user.setGroup(group);

        RespBody resPacket = new RespBody(Command.COMMAND_GET_USER_RESP, ImStatus.C10005);
        resPacket.setData(user);

//        end = System.currentTimeMillis();
//        System.out.println("获取用户信息 .. All Time:" + (end - start) + "(ms)");
        return ImKit.ConvertRespPacket(resPacket, channelContext);
    }

    @Override
    public Command command() {
        return Command.COMMAND_GET_USER_REQ;
    }

}
